#!/user/bin/python
######################
## rebin histogram ###
## Lailin, 2012 ######
######################

import sys
ROOTSYS = '/afs/atlas.umich.edu/opt/root/lib'
sys.path.append(ROOTSYS)

#####################
## Import Module  ###
#####################
import array
import os
import glob
from math import sqrt,fabs,sin,log
from ROOT import TFile,TTree,TChain,TBranch,TH1,TH1F,TList
from ROOT import TLorentzVector,TGraphAsymmErrors,TMath
from ROOT import THStack,TCanvas,TLegend,TColor,TPaveText,TPad
from ROOT import gStyle,gDirectory
from ROOT import Double

def get_hist_significance(histsig='', histbkg='', cutdirection=1, profile=1, **kw):
    ## book histogram
    nbins=histsig.GetNbinsX()
    histo_xmin=histsig.GetXaxis().GetXmin()
    histo_xmax=histsig.GetXaxis().GetXmax()
    hist_signf=TH1F('significance', 'significance', nbins, histo_xmin, histo_xmax)
    hist_signf.Sumw2()
    for i in range(1,nbins+1):
        nsig, nbkg=0, 0
        ## cut is like: xx > xx
        if cutdirection==1: 
            nsig=histsig.Integral(i, nbins)  # no overflow
            nbkg=histbkg.Integral(i, nbins)  # no overflow
        elif cutdirection==2: 
            nsig=histsig.Integral(i, nbins+1)
            nbkg=histbkg.Integral(i, nbins+1)
        elif cutdirection==-2: 
            nsig=histsig.Integral(0, i)
            nbkg=histbkg.Integral(0, i)
        elif cutdirection==-1: 
            nsig=histsig.Integral(1, i) # no underflow
            nbkg=histbkg.Integral(1, i) # no underflow
        #print "sig/bkg: ", nsig, nbkg
        signf=get_signf(nsig, nbkg, profile)
        hist_signf.SetBinContent(i, signf)

    return hist_signf

def get_signf(nsig=1, nbkg=1, profile=1,**kw):
    signf=0
    if profile==0:
        if nbkg!=0: signf=nsig/sqrt(nbkg) 
        else: signf=-1
    if profile==1:
        if nbkg!=0: signf=sqrt(2*((nsig+nbkg)*log(1+nsig/nbkg) - nsig))
        else: signf=-1
    return signf
